/************************************************************************
This file is part of Polar4linux
Copyright (C) 2010-2011 Eric jrdn2
Portions Copyright (C) 2007 Matti Juvonen <mpj@iki.fi> (RS400 Tools)
Portions Copyright (C) 2006 Jani Hursti <jani.hursti@hut.fi>,
Portions Copyright (C) 2001-2003 Tom Oliveira e Silva

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
************************************************************************/

#include "polarSettings.h"

polarSettings::polarSettings(polar4linuxInternals *internals0)
{
	internals=internals0;

	setupUi(this);
	diag=new polarConnexion(internals);
	connect(diag,SIGNAL(readyGet()),this,SLOT(getInfos()));
	connect(diag,SIGNAL(readySet()),this,SLOT(setInfos()));
	connect(diag,SIGNAL(readyDelete1()),this,SLOT(deleteSelected()));
	connect(diag,SIGNAL(readyDeleteAll()),this,SLOT(deleteAll()));
	
	connect(pushButton_getInfos, SIGNAL(clicked()), this, SLOT(askConnexionGet()));
	connect(pushButton_setInfos, SIGNAL(clicked()), this, SLOT(askConnexionSet()));
	connect(pushButtonIRDAon, SIGNAL(clicked()), this, SLOT(Connect()));
	connect(pushButtonIRDAoff, SIGNAL(clicked()), this, SLOT(Disconnect()));
	
	//connect(diag,SIGNAL(connexionDone()),this,SLOT(getInfos()));
	
	connect(comboBoxAutolap,SIGNAL(currentIndexChanged ( int )), this, SLOT(showhideAutolap(int)) );
	connect(comboBoxMeasureSpeed,SIGNAL(currentIndexChanged ( int )), this, SLOT(showhideMeasureSpeed(int)) );
	connect(comboBoxLockON,SIGNAL(currentIndexChanged ( int )), this, SLOT(showhideLockON(int)) );

	connect(pushButton_RESET, SIGNAL(clicked()), this, SLOT(Reset()));
	connect(button_getUser, SIGNAL(clicked()), this, SLOT(getUser()));
	connect(button_setUser, SIGNAL(clicked()), this, SLOT(setUser()));
	connect(button_getPlayer, SIGNAL(clicked()), this, SLOT(getPlayer()));
	connect(button_setPlayer, SIGNAL(clicked()), this, SLOT(setPlayer()));

	connect(button_getDisplay, SIGNAL(clicked()), this, SLOT(getDisplay()));
	connect(button_setDisplay, SIGNAL(clicked()), this, SLOT(setDisplay()));        

	connect(button_getGeneralSettings, SIGNAL(clicked()), this, SLOT(getGeneralSettings()));
	connect(button_setGeneralSettings, SIGNAL(clicked()), this, SLOT(setGeneralSettings()));
	connect(button_setTime, SIGNAL(clicked()), this, SLOT(setDateAndTime()));
	connect(button_getTime, SIGNAL(clicked()), this, SLOT(getDateAndTime()));
	connect(button_setStats, SIGNAL(clicked()), this, SLOT(setStats()));
	connect(button_getStats, SIGNAL(clicked()), this, SLOT(getStats()));

	connect(spinBoxSZ1up, SIGNAL(valueChanged ( int )), this, SLOT(setSportZonesTXT()));
	connect(spinBoxSZ2up, SIGNAL(valueChanged ( int )), this, SLOT(setSportZonesTXT()));
	connect(spinBoxSZ3up, SIGNAL(valueChanged ( int )), this, SLOT(setSportZonesTXT()));
	connect(spinBoxSZ4up, SIGNAL(valueChanged ( int )), this, SLOT(setSportZonesTXT()));

	connect(pushButtonGetHeaders, SIGNAL(clicked()), this, SLOT(getHeaders()));
	connect(pushButtonDeleteSelected, SIGNAL(clicked()), this, SLOT(askConnexionDeleteSelected()));
	connect(pushButtonDeleteAll, SIGNAL(clicked()), this, SLOT(askConnexionDeleteAll()));

	connect(pushButtonGetEvent, SIGNAL(clicked()), this, SLOT(getEvent()));
	connect(pushButtonSetEvent, SIGNAL(clicked()), this, SLOT(setEvent()));

	connect(pushButtonGetReminder, SIGNAL(clicked()), this, SLOT(getReminders()));
	connect(pushButtonSetReminder, SIGNAL(clicked()), this, SLOT(setReminders()));
	connect(tableWidgetReminders, SIGNAL(cellClicked (int, int)), this, SLOT(savendisplayReminder(int)));//
	connect(comboBoxExRemind, SIGNAL(currentIndexChanged ( int )), this, SLOT(showhideExToRemind(int)) );
	
	connect(tableWidgetExos2, SIGNAL(cellClicked (int, int)), this, SLOT(setSelectedExNumber(int)));//

	connect(&timer, SIGNAL(timeout()),this, SLOT(updateScreen()));
	QDateTime currentDateTime = QDateTime::currentDateTime();
	internals->gs.shift_fuse2 = 2*spinBoxFuse->value();

	dateEditEvent->setDate( currentDateTime.date() );

	tableWidgetReminders->setColumnCount(1);
	QStringList labels3;
	labels3 << tr("reminder name");
	tableWidgetReminders->setHorizontalHeaderLabels(labels3);
	tableWidgetReminders->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
	tableWidgetReminders->verticalHeader()->hide();
	tableWidgetReminders->setShowGrid(true);

	tableWidgetExos2->setColumnCount(1);
	QStringList labels2;
	labels2 << tr("Exercice description");
	tableWidgetExos2->setHorizontalHeaderLabels(labels2);
	tableWidgetExos2->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
	tableWidgetExos2->verticalHeader()->hide();
	tableWidgetExos2->setShowGrid(true);

	dateTimeEdit->setDateTime( currentDateTime );
	timer.start(1000);
	label_24->setVisible(false);
	lineEdit_autolap->setVisible(false);
	
	comboBoxMeasureSpeed->setCurrentIndex(0);
	showhideMeasureSpeed(0);
	currentDisplayedReminder=-1;
	comboBox_RemindExNum->setVisible(false);
}

/*
void polarSettings::askConnexion()
{
	diag->checkConnexion(0);
}
*/

void polarSettings::closeEvent(QCloseEvent *)
{
	if (internals->IRDAok==1) Disconnect();
}

void polarSettings::askConnexionGet()
{
	diag->checkConnexion(1);
}

void polarSettings::askConnexionSet()
{
	diag->checkConnexion(2);
}

void polarSettings::askConnexionDeleteSelected()
{
	diag->checkConnexion(3);
}

void polarSettings::askConnexionDeleteAll()
{
	diag->checkConnexion(4);
}


//debug purpose only
void polarSettings::Connect()
{
	diag->expectedSignal=0;
	diag->initIRDA();
}

//debug purpose only
void polarSettings::Disconnect()
{
	diag->expectedSignal=-1;
	diag->closeIRDA();
}


polarSettings::~polarSettings()
{
	delete diag;
}

void polarSettings::showhideAutolap(int pos)
{
	if (pos==0)
	{
		label_24->setVisible(false);
		lineEdit_autolap->setVisible(false);
	}
	else
	{
		label_24->setVisible(true);
		lineEdit_autolap->setVisible(true);
	}
}

void polarSettings::showhideMeasureSpeed(int pos)
{
	groupBox_speedOpts->setVisible(pos);
	showhideLockON(comboBoxLockON->currentIndex());
}

void polarSettings::showhideLockON(int pos)
{
	label_34->setVisible(pos);
	lineEdit_LockON->setVisible(pos);
}       
        
void polarSettings::getUser()
{
	//init_session();
	if (internals->IRDAok)
	{
		_getUSER(internals->user);
		//close_session();
		lineEdit->setText(QString::number(internals->user.weight));
		lineEdit_2->setText(QString::number(internals->user.height));
		dateEdit_birthday->setDate(QDate(internals->user.birth_year+1900,internals->user.birth_month,internals->user.birth_day));
		lineEdit_6->setText(QString::number(internals->user.FCmax));
		lineEdit_7->setText(QString::number(internals->user.VO2max));
		lineEdit_8->setText(QString::number(internals->user.FCmin));
		comboBoxSex->setCurrentIndex(internals->user.sex);
		comboBoxActivity->setCurrentIndex(internals->user.activity_level);
	}
}

void polarSettings::setUser()
{
	internals->user.birth_year =  dateEdit_birthday->date().year()-1900;
	internals->user.birth_month = dateEdit_birthday->date().month();
	internals->user.birth_day =   dateEdit_birthday->date().day();
	QDate2array(dateEdit_birthday,&internals->gs.dateTotalCalories[2],&internals->gs.dateTotalCalories[1],&internals->gs.dateTotalCalories[0]);
	internals->user.weight=lineEdit->text().toInt();
	internals->user.height=lineEdit_2->text().toInt();
	internals->user.FCmax=lineEdit_6->text().toInt();
	internals->user.VO2max=lineEdit_7->text().toInt();
	internals->user.FCmin=lineEdit_8->text().toInt();
	internals->user.sex=comboBoxSex->currentIndex();
	internals->user.activity_level=comboBoxActivity->currentIndex();
	//init_session();
	if (internals->IRDAok) _setUSER(internals->user);
	//close_session();
}

void polarSettings::setPlayer()
{
	std::string fname = lineEdit_12->text().toStdString();
	std::string lname = lineEdit_13->text().toStdString();

	fname.resize (10,' ');
	lname.resize (10,' ');

	strcpy((char*)internals->player.first_name,fname.c_str());
	strcpy((char*)internals->player.last_name,lname.c_str());
	internals->player.player_number=lineEdit_11->text().toInt();

	//init_session();
	if (internals->IRDAok) _setPlayer(internals->player);
	//close_session();
}

void polarSettings::getPlayer()
{
	//init_session();
	if (internals->IRDAok)
	{
		_getPlayer(internals->player);
		//close_session();

		lineEdit_11->setText(QString::number(internals->player.player_number));
		lineEdit_12->setText(QString((char*)internals->player.first_name));
		lineEdit_13->setText(QString((char*)internals->player.last_name));
	}
}

void polarSettings::setSelectedExNumber (int row)
{
	SelectedExNumber = row;
};


void polarSettings::getDisplay()
{
	if (internals->IRDAok)
	{
		polarLINUXio_display *u;
		_getDisplay(internals->gs);

		u=&internals->gs.displaywoSpeed;
		
		checkBoxd2->setChecked(u->display2activated);
		checkBoxd3->setChecked(u->display3activated);

		comboBox_d1up->setCurrentIndex(u->display1up-1); 
		comboBox_d1mid->setCurrentIndex(u->display1middle-1); 
		comboBox_d1down->setCurrentIndex(u->display1down-1); 

		comboBox_d2up->setCurrentIndex(u->display2up-1);  
		comboBox_d2mid->setCurrentIndex(u->display2middle-1); 
		comboBox_d2down->setCurrentIndex(u->display2down-1); 

		comboBox_d3up->setCurrentIndex(u->display3up-1); 
		comboBox_d3mid->setCurrentIndex(u->display3middle-1); 
		comboBox_d3down->setCurrentIndex(u->display3down-1);
		
		u=&internals->gs.displaywSpeed;
		
		checkBoxd2_2->setChecked(u->display2activated);
		checkBoxd3_2->setChecked(u->display3activated);
		checkBoxd4_2->setChecked(u->display4activated);
		checkBoxd5_2->setChecked(u->display5activated);
		
		comboBox_d1up_2->setCurrentIndex(u->display1up-1); 
		comboBox_d1mid_2->setCurrentIndex(u->display1middle-1); 
		comboBox_d1down_2->setCurrentIndex(u->display1down-1); 

		comboBox_d2up_2->setCurrentIndex(u->display2up-1);  
		comboBox_d2mid_2->setCurrentIndex(u->display2middle-1); 
		comboBox_d2down_2->setCurrentIndex(u->display2down-1); 

		comboBox_d3up_2->setCurrentIndex(u->display3up-1); 
		comboBox_d3mid_2->setCurrentIndex(u->display3middle-1); 
		comboBox_d3down_2->setCurrentIndex(u->display3down-1);
		
		comboBox_d4up_2->setCurrentIndex(u->display4up-1); 
		comboBox_d4mid_2->setCurrentIndex(u->display4middle-1); 
		comboBox_d4down_2->setCurrentIndex(u->display4down-1);
		
		comboBox_d5up_2->setCurrentIndex(u->display5up-1); 
		comboBox_d5mid_2->setCurrentIndex(u->display5middle-1); 
		comboBox_d5down_2->setCurrentIndex(u->display5down-1);
	}
}

void polarSettings::getGeneralSettings()
{
	//init_session();
	if (internals->IRDAok)
	{
		_getGeneralSettings(internals->gs);
		//close_session();

		comboBoxUnits->setCurrentIndex(internals->gs.units);
		comboBoxScreen->setCurrentIndex(internals->gs.showScreenName);
		comboBoxAutoLock->setCurrentIndex(internals->gs.autoLock);
		comboBoxZoneWarning->setCurrentIndex(internals->gs.zoneWarning);
		comboBoxOptionsLock->setCurrentIndex(internals->gs.optionsLock);

		comboBoxBip->setCurrentIndex(internals->gs.bipButton);
		comboBoxLanguage->setCurrentIndex(internals->gs.language);
		comboBoxHeartTouch->setCurrentIndex(internals->gs.hearttouch-1);

		comboBoxSampleRate->setCurrentIndex(internals->gs.sampleRate);
		comboBoxAutolap->setCurrentIndex(internals->gs.autolap);
		comboBoxSpeedOrPace->setCurrentIndex(internals->gs.speedOrPace);
		lineEdit_autolap->setText(QString::number(internals->gs.autolapDistance));
		comboBoxHRformat->setCurrentIndex(internals->gs.HRFormat);
		comboBoxEstimatedFCMax->setCurrentIndex(internals->gs.estimatedFCMax);
		comboBoxMeasureSpeed->setCurrentIndex(internals->gs.measureSpeed);
		comboBoxShoes->setCurrentIndex(internals->gs.shoes);
		comboBoxLockON->setCurrentIndex(internals->gs.lockON);

		lineEdit_sh1->setText(QString((char*)internals->gs.sh1));
		lineEdit_sh2->setText(QString((char*)internals->gs.sh2));

		lineEdit_sh1km->setText(QString::number(internals->gs.sh1km));
		lineEdit_sh2km->setText(QString::number(internals->gs.sh2km));


		dateEdit_sh1->setDate(QDate(internals->gs.sh1date[2]+2000,internals->gs.sh1date[1],internals->gs.sh1date[0]));
		dateEdit_sh2->setDate(QDate(internals->gs.sh2date[2]+2000,internals->gs.sh2date[1],internals->gs.sh2date[0]));

		lineEdit_LockON->setText(QString::number(internals->gs.lockONpaceValue));
		lineEdit_calibration->setText(QString::number(internals->gs.calibration));

		spinBoxSZ1low->setValue(internals->gs.sportZvalues[0]);
		spinBoxSZ1up->setValue(internals->gs.sportZvalues[1]);
		spinBoxSZ2up->setValue(internals->gs.sportZvalues[2]);
		spinBoxSZ3up->setValue(internals->gs.sportZvalues[3]);
		spinBoxSZ4up->setValue(internals->gs.sportZvalues[4]);
		spinBoxSZ5up->setValue(internals->gs.sportZvalues[5]);
	}
}


void polarSettings::setDisplay()
{
	polarLINUXio_display *u;
	//without speed measurements
	{
	u=&internals->gs.displaywoSpeed;
	
	u->display1up=comboBox_d1up->currentIndex()+1; 
	u->display1middle=comboBox_d1mid->currentIndex()+1;
	u->display1down=comboBox_d1down->currentIndex()+1;

	u->display2up=comboBox_d2up->currentIndex()+1;
	u->display2middle=comboBox_d2mid->currentIndex()+1;
	u->display2down=comboBox_d2down->currentIndex()+1;

	u->display3up=comboBox_d3up->currentIndex()+1;
	u->display3middle=comboBox_d3mid->currentIndex()+1;
	u->display3down=comboBox_d3down->currentIndex()+1;

/*
	u->display4up=0;
	u->display4middle=0;
	u->display4down=0;

	u->display5up=0;
	u->display5middle=0;
	u->display5down=0;

	u->display6up=0;
	u->display6middle=0;
	u->display6down=0;
*/
	u->display2activated=checkBoxd2->isChecked ();
	u->display3activated=checkBoxd3->isChecked ();
	u->display4activated=0;
	u->display5activated=0;
	u->display6activated=0;
	}
	//with speed measurements
	{
	u=&internals->gs.displaywSpeed;
	
	u->display1up=comboBox_d1up_2->currentIndex()+1; 
	u->display1middle=comboBox_d1mid_2->currentIndex()+1;
	u->display1down=comboBox_d1down_2->currentIndex()+1;

	u->display2up=comboBox_d2up_2->currentIndex()+1;
	u->display2middle=comboBox_d2mid_2->currentIndex()+1;
	u->display2down=comboBox_d2down_2->currentIndex()+1;

	u->display3up=comboBox_d3up_2->currentIndex()+1;
	u->display3middle=comboBox_d3mid_2->currentIndex()+1;
	u->display3down=comboBox_d3down_2->currentIndex()+1;

	u->display4up=comboBox_d4up_2->currentIndex()+1;
	u->display4middle=comboBox_d4mid_2->currentIndex()+1;
	u->display4down=comboBox_d4down_2->currentIndex()+1;

	u->display5up=comboBox_d5up_2->currentIndex()+1;
	u->display5middle=comboBox_d5mid_2->currentIndex()+1;
	u->display5down=comboBox_d5down_2->currentIndex()+1;
/*
	u->display6up=0;
	u->display6middle=0;
	u->display6down=0;
*/	
	u->display2activated=checkBoxd2_2->isChecked ();
	u->display3activated=checkBoxd3_2->isChecked ();
	u->display4activated=checkBoxd4_2->isChecked ();
	u->display5activated=checkBoxd5_2->isChecked ();
	u->display6activated=0;
	}
	
	if (internals->IRDAok) _setDisplay(internals->gs);
}
        

void polarSettings::setGeneralSettings()
{
	std::string sh1 = lineEdit_sh1->text().toStdString ();
	std::string sh2 = lineEdit_sh2->text().toStdString ();
	sh1.resize (9,' ');
	sh2.resize (9,' ');
	strcpy((char*)internals->gs.sh1,sh1.c_str());
	strcpy((char*)internals->gs.sh2,sh2.c_str());

	internals->gs.sh1km = lineEdit_sh1km->text().toInt();
	internals->gs.sh2km = lineEdit_sh2km->text().toInt();

	QDate2array(dateEdit_sh1,&internals->gs.sh1date[2],&internals->gs.sh1date[1],&internals->gs.sh1date[0]);
	QDate2array(dateEdit_sh2,&internals->gs.sh2date[2],&internals->gs.sh2date[1],&internals->gs.sh2date[0]);

	internals->gs.calibration = lineEdit_calibration->text().toInt();
	internals->gs.sampleRate=comboBoxSampleRate->currentIndex();
	internals->gs.autolap=comboBoxAutolap->currentIndex();
	internals->gs.speedOrPace=comboBoxSpeedOrPace->currentIndex();//(pace=0, speed=1)
	internals->gs.autolapDistance = lineEdit_autolap->text().toInt(); //==1 km .should it be converted???
	internals->gs.HRFormat=comboBoxHRformat->currentIndex();; //0=absolute, 1 HRMaxpercent
	internals->gs.estimatedFCMax=comboBoxEstimatedFCMax->currentIndex();; //1 true, 0 false
	internals->gs.measureSpeed=comboBoxMeasureSpeed->currentIndex();;//footpod or not
	internals->gs.shoes=comboBoxShoes->currentIndex();; //(first pair=0; second pair=1
	internals->gs.lockON=comboBoxLockON->currentIndex();; //01=pace, 00=sportzone
	internals->gs.lockONpaceValue = lineEdit_LockON->text().toInt(); //+-pace value for mode locking


	internals->gs.units =comboBoxUnits->currentIndex(); //1=lb 0=kg
	internals->gs.showScreenName=comboBoxScreen->currentIndex(); //0 no show, 1 show
	internals->gs.autoLock=comboBoxAutoLock->currentIndex(); //1 autolock, 0 no
	internals->gs.zoneWarning=comboBoxZoneWarning->currentIndex();//0 zone warning, 1 no
	internals->gs.optionsLock=comboBoxOptionsLock->currentIndex();  //0 optionsLock, 1 no
	internals->gs.bipButton=comboBoxBip->currentIndex(); //0=bip, 1=silent
	internals->gs.language=comboBoxLanguage->currentIndex(); //00=english, 01=german, 02=spanish, 03=french 04=spanish??
	internals->gs.hearttouch=comboBoxHeartTouch->currentIndex()+1; //5=inutilise, 4=light, 3=changer affichage, 2=enr. lap, 1=zone;

	internals->gs.sportZvalues[0] = spinBoxSZ1low->value();
	internals->gs.sportZvalues[1] = spinBoxSZ1up->value();
	internals->gs.sportZvalues[2] = spinBoxSZ2up->value();
	internals->gs.sportZvalues[3] = spinBoxSZ3up->value();
	internals->gs.sportZvalues[4] = spinBoxSZ4up->value();
	internals->gs.sportZvalues[5] = spinBoxSZ5up->value();

	//init_session();
	if (internals->IRDAok) _setGeneralSettings(internals->gs);
	//close_session();
}


void polarSettings::updateScreen()
{
	QDateTime currentDateTime = QDateTime::currentDateTime();
	dateTimeEdit->setDateTime( currentDateTime );
}


void polarSettings::setDateAndTime()
{
	QDateTime currentDateTime = QDateTime::currentDateTime();

	internals->gs.year = currentDateTime.date().year()-2000;
	internals->gs.month = currentDateTime.date().month();
	internals->gs.day = currentDateTime.date().day();
	internals->gs.hour =currentDateTime.time().hour();
	internals->gs.minute = currentDateTime.time().minute();
	internals->gs.second = currentDateTime.time().second();

	int tmp = 2*spinBoxFuse->value();
	if (tmp<0) internals->gs.shift_fuse2 = 256-tmp;
	else internals->gs.shift_fuse2 = tmp;

	internals->gs.display12h=checkBox_timeDisplay->isChecked();
	internals->gs.wakeUpMin = timeEditWakeUP->time().minute();
	internals->gs.wakeUpHour = timeEditWakeUP->time().hour();
	internals->gs.wakeUpOn = checkBoxWakeUP->isChecked()*(comboBoxWakeUP->currentIndex()+1);

	//init_session();
	if (internals->IRDAok) _setDateAndTime(internals->gs);
	//close_session();
}

void polarSettings::getDateAndTime()
{
	//init_session();
	if (internals->IRDAok)
	{
		_getDateAndTime(internals->gs);
		//close_session();

		timeEditWakeUP->setTime(QTime(internals->gs.wakeUpHour,internals->gs.wakeUpMin));
		checkBox_timeDisplay->setChecked(internals->gs.display12h);
		
		if (internals->gs.wakeUpOn != 0x00)
		{
			checkBoxWakeUP->setChecked(true);
			comboBoxWakeUP->setCurrentIndex(internals->gs.wakeUpOn-1);
			}

		double t;
		if (internals->gs.shift_fuse2>128) t = -(double)(256-internals->gs.shift_fuse2)/2.0;
		else t = (double)(internals->gs.shift_fuse2)/2.0; 
		spinBoxFuse->setValue(t);
	}
}

void polarSettings::setStats()
{
	internals->gs.Totaldistance = lineEdit_StatsDistance->text().toInt();
	internals->gs.caloriesTotal = lineEdit_Calories->text().toInt();
	internals->gs.sh1km = lineEdit_sh1b->text().toInt();
	internals->gs.sh2km = lineEdit_sh2b->text().toInt();
	internals->gs.hoursTotal = lineEdit_StatsHour->text().toInt();
	internals->gs.minutesTotal = lineEdit_StatsMinute->text().toInt();
	internals->gs.exerciseTotal = lineEdit_NumEx->text().toInt();

	QDate2array(dateEditStartTotalTime,&internals->gs.dateTotalDuration[2],&internals->gs.dateTotalDuration[1],&internals->gs.dateTotalDuration[0]);
	QDate2array(dateEditStartTotalDistance,&internals->gs.dateTotaldistance[2],&internals->gs.dateTotaldistance[1],&internals->gs.dateTotaldistance[0]);
	QDate2array(dateEditStartTotalCalories,&internals->gs.dateTotalCalories[2],&internals->gs.dateTotalCalories[1],&internals->gs.dateTotalCalories[0]);
	QDate2array(dateEditStartTotalExercises,&internals->gs.dateTotalExercises[2],&internals->gs.dateTotalExercises[1],&internals->gs.dateTotalExercises[0]);
	QDate2array(dateEditStartTotalShoes1,&internals->gs.dateshoes1[2],&internals->gs.dateshoes1[1],&internals->gs.dateshoes1[0]);
	QDate2array(dateEditStartTotalShoes2,&internals->gs.dateshoes2[2],&internals->gs.dateshoes2[1],&internals->gs.dateshoes2[0]);

	//init_session();
	if (internals->IRDAok) _setStats(internals->gs);
	//close_session();
}


void polarSettings::getStats()
{
	//init_session();
	if (internals->IRDAok)
	{
		_getStats(internals->gs);
		//close_session();

		lineEdit_StatsDistance->setText(QString::number(internals->gs.Totaldistance));
		lineEdit_Calories->setText(QString::number(internals->gs.caloriesTotal));
		lineEdit_sh1b->setText(QString::number(internals->gs.sh1km));
		lineEdit_sh2b->setText(QString::number(internals->gs.sh2km));
		lineEdit_StatsHour->setText(QString::number(internals->gs.hoursTotal));
		lineEdit_StatsMinute->setText(QString::number(internals->gs.minutesTotal));
		lineEdit_NumEx->setText(QString::number(internals->gs.exerciseTotal));


		dateEditStartTotalTime->setDate(QDate(internals->gs.dateTotalDuration[2]+2000,internals->gs.dateTotalDuration[1],internals->gs.dateTotalDuration[0]));
		dateEditStartTotalDistance->setDate(QDate(internals->gs.dateTotaldistance[2]+2000,internals->gs.dateTotaldistance[1],internals->gs.dateTotaldistance[0]));
		dateEditStartTotalCalories->setDate(QDate(internals->gs.dateTotalCalories[2]+2000,internals->gs.dateTotalCalories[1],internals->gs.dateTotalCalories[0]));
		dateEditStartTotalExercises->setDate(QDate(internals->gs.dateTotalExercises[2]+2000,internals->gs.dateTotalExercises[1],internals->gs.dateTotalExercises[0]));
		dateEditStartTotalShoes1->setDate(QDate(internals->gs.dateshoes1[2]+2000,internals->gs.dateshoes1[1],internals->gs.dateshoes1[0]));
		dateEditStartTotalShoes2->setDate(QDate(internals->gs.dateshoes2[2]+2000,internals->gs.dateshoes2[1],internals->gs.dateshoes2[0]));
	}
}

void polarSettings::QDate2array(QDateEdit *&edit,unsigned char *yy,unsigned char *mm,unsigned char *dd)
{
	*yy = (edit->date().year()-2000);
	*mm = edit->date().month();
	*dd = edit->date().day();
}

void polarSettings::getHeaders()
{
	//init_session();
	if (internals->IRDAok)
	{
		//tableWidgetExos2->clear();
		for (int i=tableWidgetExos2->rowCount()-1;i>=0;--i) tableWidgetExos2->removeRow(i);

		int nb = _getNumberOfExercises();
		for (int i=0;i<nb;i++)
		{
			QTableWidgetItem *name = new QTableWidgetItem(_getHeader(i).c_str());
			name->setFlags(Qt::ItemIsEnabled);
			int row = tableWidgetExos2->rowCount();
			tableWidgetExos2->insertRow(row);
			tableWidgetExos2->setItem(row, 0, name);
		}
	}
	//close_session();
}

void polarSettings::deleteSelected()
{
	diag->setMaximum(1);
	diag->setProgress(0);
	diag->drawStatus(tr("Deleting selected sessions"));
	
	//init_session();
	if (internals->IRDAok)
	{
		_deleteExercise(SelectedExNumber);
		tableWidgetExos2->removeRow(SelectedExNumber);
	}
	diag->setProgress(1);
	if (internals->autodisconnect==true) diag->closeIRDA();
	diag->hide();
}

void polarSettings::deleteAll()
{
	diag->setMaximum(1);
	diag->setProgress(0);
	diag->drawStatus(tr("Deleting all sessions"));
	//init_session();
	if (internals->IRDAok)
	{
		_deleteAll();
		//tableWidgetExos2->clear();
		for (int i=tableWidgetExos2->rowCount()-1;i>=0;--i) tableWidgetExos2->removeRow(i);
	}
	diag->setProgress(1);
	if (internals->autodisconnect==true) diag->closeIRDA();
	diag->hide();
}




void polarSettings::getEvent()
{
	//init_session();
	if (internals->IRDAok)
	{
		_getEvent(internals->gs.event);
		//close_session();

		lineEdit_eventName->setText(QString((char*)internals->gs.event.eventName));
		QDate theDate = QDate::currentDate();
		dateEditEvent->setDate(theDate.addDays(internals->gs.event.numdays));
		checkBoxActiveEvent->setChecked(internals->gs.event.isActive) ;
	}
}

void polarSettings::setEvent()
{
	//get today's date from display
	std::string chaine = lineEdit_eventName->text().toStdString();
	chaine.resize (10,' ');

	memcpy(internals->gs.event.eventName,chaine.c_str(),10);
	QDate theDate = QDate::currentDate();
	internals->gs.event.numdays = theDate.daysTo(dateEditEvent->date());
	internals->gs.event.isActive=checkBoxActiveEvent->isChecked();
	//init_session();
	if (internals->IRDAok) _setEvent(internals->gs.event);
	//close_session();
}

void polarSettings::showhideExToRemind(int row)
{
	if (row==0 || row==1) comboBox_RemindExNum->setVisible(false);
	if (row==2 || row==3) comboBox_RemindExNum->setVisible(true);
}


void polarSettings::getReminders()
{
	if (internals->IRDAok)
	{
		_getReminders(internals->reminders);

		for (int i=tableWidgetReminders->rowCount()-1;i>=0;--i) tableWidgetReminders->removeRow(i);
		for (int i=0;i<7;i++)
		{
			QTableWidgetItem *name = new QTableWidgetItem((char*)internals->reminders.rem[i].name);
			name->setFlags(Qt::ItemIsEnabled);
			int row = tableWidgetReminders->rowCount();
			tableWidgetReminders->insertRow(row);
			tableWidgetReminders->setItem(row, 0, name);
		}
		displayReminder(0);
	}
}

void polarSettings::setReminders()
{
	if (currentDisplayedReminder!=-1)
	{
		savendisplayReminder (currentDisplayedReminder);
		//init_session();
		if (internals->IRDAok) _setReminders(internals->reminders);
		//close_session();
	}
}

void polarSettings::savendisplayReminder (int row)
{
	//save last one if displayed
	if (currentDisplayedReminder!=-1) saveReminder(currentDisplayedReminder);
	displayReminder(row);
}

void polarSettings::displayReminder (int row)
{
	//change displayed exercise
	currentDisplayedReminder = row;
	polarLINUXio_reminder *p =&internals->reminders.rem[row];

	lineEdit_ReminderName->setText((char*)p->name);

	if (p->bipstyle == 0x80) comboBoxSoundReminder->setCurrentIndex(0);
	else if (p->bipstyle == 0x20) comboBoxSoundReminder->setCurrentIndex(1);
	else comboBoxSoundReminder->setCurrentIndex(2);

	comboBoxRepeatReminder->setCurrentIndex(p->repeatMode-1);

	if (p->remindAt == 8) comboBoxAlarmReminder->setCurrentIndex(3);
	else if (p->remindAt == 4) comboBoxAlarmReminder->setCurrentIndex(2);
	else if (p->remindAt == 2) comboBoxAlarmReminder->setCurrentIndex(1);
	else comboBoxAlarmReminder->setCurrentIndex(0);

	int extype = p->repeatExercise/10;
	if (extype == 4) extype = 3;
	comboBoxExRemind->setCurrentIndex(extype);
	comboBox_RemindExNum->setCurrentIndex(p->repeatExercise%10);

	if (p->repeatExercise/10 ==0 || p->repeatExercise/10 ==1) comboBox_RemindExNum->setVisible(false);
	else comboBox_RemindExNum->setVisible(true);

	checkBoxReminder->setChecked(p->active);

	unsigned char dd,mm,yy;
	hex2ddmmyy(p->date[0],p->date[1],&dd,&mm,&yy);

	dateTimeEditReminder->setDate(QDate(yy+2000,mm,dd));
	dateTimeEditReminder->setTime(QTime(hexa_to_same_decimal(p->time[1]),hexa_to_same_decimal(p->time[0])));
};


void polarSettings::saveReminder (int current)
{
	polarLINUXio_reminder *p =&internals->reminders.rem[current];

	if (comboBoxSoundReminder->currentIndex()==0) p->bipstyle = 0x80;
	else if (comboBoxSoundReminder->currentIndex()==1) p->bipstyle = 0x20;
	else p->bipstyle = 0x40;

	p->repeatMode = comboBoxRepeatReminder->currentIndex()+1;

	if (comboBoxAlarmReminder->currentIndex()==0) p->remindAt = 1;
	else if (comboBoxAlarmReminder->currentIndex()==1) p->remindAt = 2;
	else if (comboBoxAlarmReminder->currentIndex()==2) p->remindAt = 4;
	else p->remindAt = 8;

	int extype = comboBoxExRemind->currentIndex();
	if (extype == 3) extype = 4;

	p->repeatExercise = 10*extype + comboBox_RemindExNum->currentIndex();
	p->active = checkBoxReminder->isChecked();

	unsigned char dd,mm,yy;
	QDate tmp = dateTimeEditReminder->date();
	dd=dateTimeEditReminder->date().day();
	mm=dateTimeEditReminder->date().month();
	yy=dateTimeEditReminder->date().year()-2000;

	ddmmyy2hex(dd,mm,yy,&p->date[0],&p->date[1]);
	p->time[1] = decimal_to_same_hexa(dateTimeEditReminder->time().hour());
	p->time[0] = decimal_to_same_hexa(dateTimeEditReminder->time().minute());


	std::string namestd = lineEdit_ReminderName->text().toStdString(); 
	tableWidgetReminders->item(current,0)->setText(lineEdit_ReminderName->text());
	namestd.resize (10,' ');
	memcpy(p->name,namestd.c_str(),10);


	if (comboBoxSoundReminder->currentIndex()==0) p->bipstyle = 0x80;
	else if (comboBoxSoundReminder->currentIndex()==1) p->bipstyle = 0x20;
	else  p->bipstyle = 0x40;
}

void polarSettings::Reset()
{
	if (internals->IRDAok==1)
	{
		RS400_factoryreset();
		RS400_close_session();
		internals->IRDAok = 0;
	}
}


void polarSettings::getInfos()
{
	diag->setMaximum(9);
	diag->setProgress(0);
	diag->drawStatus(tr("Downloading User"));
	getUser();
	
	diag->setProgress(1);
	diag->drawStatus(tr("Downloading Player"));
	getPlayer();
	
	diag->setProgress(2);
	diag->drawStatus(tr("Downloading General settings"));
	getGeneralSettings();
	
	diag->setProgress(3);
	diag->drawStatus(tr("Downloading Date and time"));
	getDateAndTime();
	
	diag->setProgress(4);
	diag->drawStatus(tr("Downloading statistics"));
	getStats();
	
	diag->setProgress(5);
	diag->drawStatus(tr("Downloading displays"));
	getDisplay();
	
	diag->setProgress(6);
	diag->drawStatus(tr("Downloading session headers"));
	getHeaders();
	
	diag->setProgress(7);
	diag->drawStatus(tr("Downloading events"));
	getEvent();
	
	diag->setProgress(8);
	diag->drawStatus(tr("Downloading reminders"));
	getReminders();
	
	diag->setProgress(9);
	diag->drawStatus(tr("done"));
	diag->hide();
	if (internals->autodisconnect==true) diag->closeIRDA();
}

void polarSettings::setInfos()
{
	diag->setMaximum(8);
	diag->setProgress(0);
	diag->drawStatus(tr("Uploading Player"));
	setPlayer();
	
	diag->setProgress(1);
	diag->drawStatus(tr("Uploading User"));
	setUser();
	
	diag->setProgress(2);
	diag->drawStatus(tr("Uploading General settings"));
	setGeneralSettings();
	
	diag->setProgress(3);
	diag->drawStatus(tr("Uploading Date and time"));
	setDateAndTime();
	
	diag->setProgress(4);
	diag->drawStatus(tr("Uploading statistics"));
	setStats();
	
	diag->setProgress(5);
	diag->drawStatus(tr("Uploading displays"));
	setDisplay();
	
	diag->setProgress(6);
	diag->drawStatus(tr("Uploading events"));
	setEvent();
	
	diag->setProgress(7);
	diag->drawStatus(tr("Uploading reminders"));
	setReminders();
	
	diag->setProgress(8);
	diag->drawStatus(tr("done"));
	diag->hide();
	if (internals->autodisconnect==true) diag->closeIRDA();
}

void polarSettings::setSportZonesTXT()
{
	lineEdit_SZ2low->setText(QString::number(spinBoxSZ1up->value()+1));
	lineEdit_SZ3low->setText(QString::number(spinBoxSZ2up->value()+1));
	lineEdit_SZ4low->setText(QString::number(spinBoxSZ3up->value()+1));
	lineEdit_SZ5low->setText(QString::number(spinBoxSZ4up->value()+1));
}
